package com.w4cms.model;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
import com.w4cms.utils.Tools;

public class SysMenu extends Model<SysMenu> {
	private static final long serialVersionUID = -2091934946600293540L;
	public static final SysMenu dao = new SysMenu();
	
	public List<Map<String,Object>> getMenuList(Object pid){
		List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
		List<SysMenu> ms = null;
		if(pid!=null){
			ms = dao.find("select id,name,parent_id as pId from sys_menu where status!=-1 and parent_id=?", pid);
		}else{
			ms = dao.find("select id,name,parent_id as pId from sys_menu where status!=-1");
		}
		for (SysMenu sysMenu : ms) {
			list.add(sysMenu.getAttrs());
		}
		return list;
	}
	
	public Page<SysMenu> searchMenus(int pageNumber,int  pageSize,String search){
		if(Tools.isEmpty(search))
			return dao.paginate(pageNumber, pageSize, "select * ", " from sys_menu where status!=-1");
		else
			return dao.paginate(pageNumber, pageSize, "select * ", " from sys_menu where status!=-1 and name like ? ","%"+search+"%");
	}
	public List<TreeData> searchMenuTree(String search){
		List<TreeData> list = new ArrayList<TreeData>();
		List<SysMenu> ms = null;
		if(Tools.isEmpty(search))
			ms = dao.find("select * from sys_menu where status!=-1");
		else
			ms = dao.find("select * from sys_menu where status!=-1 and name like ? ","%"+search+"%");
		for (SysMenu sysMenu : ms) {
			TreeData data = new TreeData();
			data.setId(sysMenu.getInt("id").toString());
			data.setPid(sysMenu.getInt("parent_id").toString());
			data.setText(sysMenu.getStr("name"));
			data.setUrl(sysMenu.getStr("url"));
			data.getAttributes().put("status", sysMenu.get("status"));
			data.getAttributes().put("remark", sysMenu.get("remark"));
			data.getAttributes().put("menu_order", sysMenu.get("menu_order"));
			data.getAttributes().put("create_time", sysMenu.get("create_time"));
			data.getAttributes().put("update_time", sysMenu.get("update_time"));
			list.add(data);
		}
		return TreeData.formatTree3(list);
	}
	
	public List<TreeData> menuTree(Object pid){
		List<TreeData> list = new ArrayList<TreeData>();
		List<SysMenu> ms = null;
		if(pid!=null){
			ms = dao.find("select id,name,parent_id as pId from sys_menu where status!=-1 and parent_id=?", pid);
		}else{
			ms = dao.find("select id,name,parent_id as pId from sys_menu where status!=-1");
		}
		
		for (SysMenu sysMenu : ms) {
			TreeData data = new TreeData();
			data.setId(sysMenu.getInt("id").toString());
			data.setPid(sysMenu.getInt("pId").toString());
			data.setText(sysMenu.getStr("name"));
			list.add(data);
		}
		return TreeData.formatTree3(list);
	}
}
